package com.movie.controller;

import com.movie.dao.UserDao;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginController extends HttpServlet {
    private UserDao userDao;

    @Override
    public void init() throws ServletException {
        userDao = new UserDao();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 如果已登录，直接跳转到电影列表页面
        if (request.getSession().getAttribute("user") != null) {
            response.sendRedirect("movie?action=list");
            return;
        }
        // 如果未登录，跳转到登录页面
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (userDao.checkLogin(username, password)) {
            // 登录成功，存储用户名到 session
            request.getSession().setAttribute("user", username);
            response.sendRedirect("movie?action=list"); // 跳转到电影列表页面
        } else {
            // 登录失败，显示错误信息
            request.setAttribute("error", "Invalid username or password");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}
